
//
//  StatusCell.swift
//  LX_weibo
//
//  Created by LTT❤️ on 15/7/4.
//  Copyright © 2015年 LTT. All rights reserved.
//

import UIKit
import FFAutoLayout
import SDWebImage

let LTStatusForwardCellIdentifier = "LTStatusForwardCellIdentifier"
let LTStatusNormalCellIdentifier = "LTStatusNormalCellIdentifier"
private let LTforCellWithReuseIdentifier = "LTforCellWithReuseIdentifier"
class StatusCell: UITableViewCell , UICollectionViewDataSource {
    
    
   ///配图视图宽度约束
    var widthCons:NSLayoutConstraint?
    ///配图视图高度约束
    var heightCons:NSLayoutConstraint?
    
    ///配图顶部高度约束
    var topCons:NSLayoutConstraint?
    
    ///转发微博标签
    var forwardLabel = UILabel()
    //原创微博 cell
  
    
    
    //获取数据模型
    
    
    
    
    var  status:Status?
        {
        didSet{
            //设置头像
            if  let urlString = status?.user?.profile_image_url{
               iconView.sd_setImageWithURL(NSURL(string: urlString))
            }
            
            forwardLabel.text = (status?.retweeted_status?.user?.name ?? "") + ":" + (status?.retweeted_status?.text ?? "")
            //设置认证
            vipIconView.image = status?.user?.verifiedImage
            //设置会员
            memberIconView.image = status?.user?.mbImage
            nameLabel.text = status?.user?.name
            timeLabel.text = "刚刚"
            sourceLabel.text = "来自,微博"
            contentLabel.text = status?.text
            let result = calcPictureViewSize(status!)
            topCons?.constant = result.viewSize.height == 0 ? 0:12
            widthCons?.constant = result.viewSize.width
            heightCons?.constant = result.viewSize.height
            pictureLayout.itemSize = result.itemSize
            pictureView.reloadData()
        }
    }
    
    
    class func cellIdentifier(status:Status) -> String{
        return status.retweeted_status != nil ? LTStatusForwardCellIdentifier:LTStatusNormalCellIdentifier
    }
    
    
    
    
    ///计算行高
    func rowHeight(status:Status) -> CGFloat {
        self.status = status
        layoutIfNeeded()
        return CGRectGetMaxY(footerView.frame)
    }
    
    
    
    
    //MARK:数据源
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return  status?.picURLs?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(LTforCellWithReuseIdentifier, forIndexPath: indexPath)as! StatusPictureCell
        //调用此数据源方法,说明上面的数据行数
        cell.imageURL = status?.picURLs![indexPath.item]
        return cell 
    }
    
    
    //根据微博模型计算图片大小
    private func calcPictureViewSize(status:Status) -> (viewSize:CGSize,itemSize:CGSize){
        let itemSize = CGSize(width: 90, height: 90)
        let margin:CGFloat = 10        //获取图片数量
        let count = status.picURLs?.count ?? 0
        //没图
        if count == 0 {
            return (CGSizeZero,itemSize)
        }
        //单图
        if count == 1
        {
            //拿到并且创建image key 就是url字符串
            let key = status.picURLs![0].absoluteString
            
           let image =  SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            return (image.size,image.size)
        }
        
        //四图
        if count == 4
        {
            let W = itemSize.width * 2 + margin
            return (CGSize(width: W, height: W),itemSize)
            
        }
        //多图
        let rowCount = 3
        let row = (count-1)/rowCount+1
        
        let w = itemSize.width * CGFloat(rowCount) + CGFloat(rowCount - 1) * margin
        
        let h = itemSize.height * CGFloat(row )+CGFloat(row - 1) * margin
        
        return (CGSize(width: w, height: h),itemSize)
    }
    
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        let screenWidth = UIScreen.mainScreen().bounds.width
        let topView = UIView()
        topView.backgroundColor = UIColor(white: 0.5, alpha: 1.0)
        addSubview(topView)
        topView.ff_AlignInner(ff_AlignType.TopLeft, referView: self, size: CGSize(width: screenWidth, height: 10))
        
        
        addSubview(iconView)
        addSubview(nameLabel)
        addSubview(memberIconView)
        addSubview(vipIconView)
        addSubview(timeLabel)
        addSubview(sourceLabel)
        addSubview(contentLabel)
        contentLabel.preferredMaxLayoutWidth = UIScreen.mainScreen().bounds.width
        addSubview(pictureView)
        addSubview(footerView)
        footerView.backgroundColor = UIColor(white: 0.95, alpha: 1.0)
        preparePictureView()
        
        
        iconView.ff_AlignInner(ff_AlignType.TopLeft, referView: self, size: CGSize(width: 34, height: 34),offset:CGPoint(x: 12, y: 12))
        nameLabel.ff_AlignHorizontal(ff_AlignType.TopRight, referView: iconView, size: nil, offset: CGPoint(x: 12, y: 0))
        memberIconView.ff_AlignHorizontal(ff_AlignType.CenterRight, referView: nameLabel, size: nil, offset: CGPoint(x: 12, y: 0))
        vipIconView.ff_AlignInner(ff_AlignType.BottomRight, referView: iconView, size: nil, offset: CGPoint(x: 8, y: 8))
        timeLabel.ff_AlignHorizontal(ff_AlignType.BottomRight, referView: iconView, size: nil, offset: CGPoint(x: 12, y: 0))
        sourceLabel.ff_AlignHorizontal(ff_AlignType.CenterRight
            , referView: timeLabel, size: nil, offset: CGPoint(x: 12, y: 0))
        contentLabel.ff_AlignVertical(ff_AlignType.BottomLeft, referView: iconView, size: nil, offset: CGPoint(x: 0, y: 12))
        //contentLabel.ff_AlignInner(ff_AlignType.BottomRight, referView: self, size: nil, offset: CGPoint(x: -8, y: -8))
//   let cons  = pictureView.ff_AlignVertical(ff_AlignType.BottomLeft, referView: contentLabel, size: CGSize(width: 290, height: 90), offset: CGPoint(x: 0, y: 12))
//    widthCons = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Width)
//    heightCons = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Height)
//        pictureView.ff_AlignInner(ff_AlignType.BottomRight, referView: self, size: nil, offset: CGPoint(x: -8, y: -8))
       footerView.ff_AlignVertical(ff_AlignType.BottomLeft, referView: pictureView, size: CGSize(width: screenWidth, height: 44), offset: CGPoint(x: -12, y: 12))
        
        
        
    }
    //准备配图视图
    private func preparePictureView(){
        //1.设置背景颜色
        pictureView.backgroundColor = UIColor.lightGrayColor()
        //2.数据源
        pictureView.dataSource = self
        
        
        //3.注册可重用cell
        
        pictureView.registerClass(StatusPictureCell.self, forCellWithReuseIdentifier: LTforCellWithReuseIdentifier)
        //4.设置layout
        pictureLayout.minimumInteritemSpacing = 10
        pictureLayout.minimumLineSpacing = 10
        
        
    }
    
    
    
    
    
  //如果使用XIB 或者 SB开发,使用fatalerror会崩溃
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
    //MARK: - 控件的懒加载
    //头像
    lazy var iconView = UIImageView()
    //名字
    lazy var nameLabel = UILabel(textColor: UIColor.darkGrayColor(), fontSize: 14)

    //vip等级图片
    lazy var memberIconView:UIImageView = UIImageView(image: UIImage(named: "common_icon_membership_level1"))
    //右下角相关功能
    lazy var vipIconView:UIImageView = UIImageView(image: UIImage(named: "avatar_grassroot"))
    //发布时间
    lazy var timeLabel = UILabel(textColor: UIColor.orangeColor(), fontSize: 10)
    //发布来源
    lazy var sourceLabel = UILabel(textColor: UIColor.darkGrayColor(), fontSize: 10)
    //微博内容
    lazy var contentLabel :UILabel = UILabel(textColor: UIColor.darkGrayColor(), fontSize: 15, mutiLines: true)
    
    
    //图像视图
    lazy var pictureLayout  = UICollectionViewFlowLayout()
    lazy var pictureView : UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: self.pictureLayout)
    
    //页脚视图
    lazy var footerView:StatusFooterView = StatusFooterView()


}


///配图cell
private class StatusPictureCell:UICollectionViewCell{
    var imageURL:NSURL?{
        didSet{
        iconView.sd_setImageWithURL(imageURL)
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        iconView.contentMode = UIViewContentMode.ScaleAspectFill
       iconView.clipsToBounds = true
        addSubview(iconView)
        iconView.ff_Fill(self)
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
 lazy var iconView = UIImageView()
    
}

///页脚视图

 class StatusFooterView:UIView{
    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(forwardBtn)
        addSubview(commentBtn)
        addSubview(likeBtn)
        
        ff_HorizontalTile([forwardBtn,commentBtn,likeBtn], insets: UIEdgeInsetsZero)
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var forwardBtn :UIButton = UIButton(title: "转发", imageName: "timeline_icon_retweet", fontSize: 12)
    
    lazy var commentBtn :UIButton = UIButton(title: "评论", imageName: "timeline_icon_comment", fontSize: 12)
    
    lazy var likeBtn :UIButton = UIButton(title: "点赞", imageName: "timeline_icon_unlike", fontSize: 12)

    
}

    
    

